<?php

class FeedController extends Zend_Controller_Action {

    public function init() {
        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
    }

    public function rssAction() {
        $this->_feed('rss');
    }

    public function atomAction() {
        $this->_feed('atom');
    }

    protected function _feed($format) {
        $tableEntries = new Application_Model_DbTable_Entries();
        $entries = $tableEntries->fetchAll(
                        $tableEntries->select()
                        ->from(array('e' => 'entries'), array('id', 'title', 'date', 'author', 'body'))
                        ->join(array('u' => 'users'),
                                'e.user_id = u.id', array())
                        ->where('u.disabled = ?', false)
                        ->order('e.date desc')
        );
        $channel = array(
            'title' => 'zendblog',
            'link' => $this->view->baseUrl(),
            'description' => 'all blogs',
            'charset' => 'utf-8',
            'generator' => 'Zend Framework Zend_Feed',
            'lastUpdate' => time(),
            'entries' => array()
        );

        foreach ($entries as $entry) {
            //echo date('r', strtotime($entry['date']));
            $channel['entries'][] = array(
                'title' => $entry['title'],
                'link' => $this->view->baseUrl() . $this->view->entryUrl(array('user' => $entry['author'], 'blog' => $entry['title'], 'id' => $entry['id'])),
                'guid' => $entry['id'],
                'description' => ($format == 'atom') ? preg_replace('/(<.*?>)/', '', $entry['body']) : $entry['body'],
                'lastUpdate' => strtotime($entry['date'])
            );
        }

        $feed = Zend_Feed::importArray($channel, $format);
        $feed->send();
    }

}

